<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Shopping Cart</title>
    <style>
        body {
            /* 设置文本字体属性 */
            font-family: Arial, sans-serif;
        }

        h1 {
            text-align: center;
        }

        form {
            margin-bottom: 10px;
        }

        label {
            margin-right: 5px;
        }

        #cartItems {
            border: 1px solid #ccc;
            padding: 10px;
        }

        .product-item {
            margin-bottom: 5px;
        }

        #totalPrice {
            font-weight: bold;
            margin-top: 10px;
        }
    </style>
</head>

<body>
    <h1>购物车</h1>
    <div id="cartItems"></div>
    <form id="productForm">
        <label for="productName">商品名称：</label>
        <input type="text" id="productName" placeholder="输入商品名">
        <label for="productPrice">商品价格：</label>
        <input type="number" id="productPrice" placeholder="输入价格">
        <input type="button" value="添加商品" id="addProduct">
    </form>
    <div id="totalPrice">总价: 0元</div>
    <script>
        // 获取DOM元素
        const cartItemsDiv = document.getElementById('cartItems');
        const productForm = document.getElementById('productForm');
        const addProductButton = document.getElementById('addProduct');
        const totalPriceDiv = document.getElementById('totalPrice');

        let total = 0; // 用于记录总价

        // 添加商品的函数
        function addProduct(event) {
            event.preventDefault(); // 阻止表单默认提交行为

            const productName = document.getElementById('productName').value;//获取输入框的值
            const productPrice = parseFloat(document.getElementById('productPrice').value);

            if (productName && !isNaN(productPrice) && productPrice > 0) {//同时满足这几个条件
                const productItemDiv = document.createElement('div');
                productItemDiv.classList.add('product-item');
                productItemDiv.innerHTML = `<span>${productName}</span>
      <span>价格: ${productPrice} 元</span>`;
                cartItemsDiv.appendChild(productItemDiv);

                total += productPrice;
                totalPriceDiv.textContent = `总价: ${total} 元`;

                // 清空输入框
                document.getElementById('productName').value = '';
                document.getElementById('productPrice').value = '';
            }
        }

        // 给添加商品按钮添加点击事件监听器
        addProductButton.addEventListener('click', addProduct);
    </script>
</body>

</html>